package com.ddfeiyu.server.handler;

import com.alibaba.fastjson.JSON;
import com.ddfeiyu.agreement.log.LogRequest;
import com.ddfeiyu.agreement.log.LogResponse;
import com.ddfeiyu.redis.util.RedisQueueUtil;
import com.ddfeiyu.server.MyBizHandler;

import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;

public class LogHandler extends MyBizHandler<LogRequest> {

    protected Logger logger = LoggerFactory.getLogger(LogHandler.class);

    private RedisQueueUtil redisQueueUtil;

    public LogHandler(RedisQueueUtil redisQueueUtil){
        this.redisQueueUtil =  redisQueueUtil;
    }

    @Override
    public void channelRead(Channel channel, LogRequest msg) {
        try {
            logger.info("NettyServer-LogHandler-请求处理：{} ", JSON.toJSONString(msg));
            // 1. 失败返回false
            if (msg == null){
                logger.error("NettyServer-LogHandler-失败返回false：{} ", JSON.toJSONString(msg));
                // 传输消息
                channel.writeAndFlush(new LogResponse(false));
                return;
            }
            // TODO  落入es 、redis
            redisQueueUtil.enqueue(msg.getTraceId(), Arrays.asList( msg.getLog()));

            //  反馈消息
            // 组装消息包
            LogResponse logResponse = new LogResponse(true);
            // 传输消息
            channel.writeAndFlush(logResponse);
            logger.info("NettyServer-LogHandler-成功：{} ", JSON.toJSONString(msg));
        }catch (Exception e){
            logger.error("NettyServer-LogHandler-异常：{} ", JSON.toJSONString(msg), e);
        }

    }
}
